#!/bin/bash

# How to name the debug version based on the running kernel?
APPEND=-dbg
VER=$(uname -r)
MINOR_VER=$(echo $VER | sed 's/^\([0-9]\.[0-9]\+\(\.[0-9]\+\)*\).*$/\1/')
APPEND_VER=${VER#$MINOR_VER}${APPEND}

# Make sure we can execute apt-get
if ! [ -x "$(which apt-get 2>/dev/null)" ]; then
	echo "This does not seem to be a Debian based distribution!" >&2
	exit 1
fi

# How do we become root?
if [ $(id -u) == 0 ]; then
	SUDO=""
	ROOTCMD=""
else
	echo "You might be prompted for your password to install depencency packages."
	SUDO="sudo"
	ROOTCMD="--rootcmd $SUDO"
fi

# Resolve build dependencies, get source, and prepare Makefile
$SUDO apt-get -y build-dep linux-image-$VER &&
apt-get -y source linux-image-$VER &&
cd linux-*${MINOR_VER}* &&
mv Makefile Makefile.orig &&
sed \
        -e 's@^\(CFLAGS_KERNEL\s*=\)@\1 -g @' \
        -e 's@^\(AFLAGS_KERNEL\s*=\)@\1 -gdwarf-2 @' \
        Makefile.orig > Makefile

# Run parallel jobs when compiling the source
if [ -z "$CONCURRENCY_LEVEL" ]; then
       	export CONCURRENCY_LEVEL=$(( `grep -c '^processor' /proc/cpuinfo` + 1))
fi

# Compile source and create package
make-kpkg --us --uc $ROOTCMD --append-to-version $APPEND_VER --initrd kernel_image kernel_headers || exit 1

if [ -r vmlinux ]; then
	#bzip2 -9 vmlinux -c > ../vmlinux-${VER}${APPEND}.bz2 &&
	#cp -v vmlinux ../vmlinux-${VER}${APPEND} &&
	echo -e "\nGenerating object dump for vmlinux-${VER}${APPEND}..." &&
	objdump -W vmlinux 2>/dev/null | lzma -c -2 > ../objdump-${VER}${APPEND}.lzma &&
	echo "Done." || echo "Error generating objdump."
fi

